import React, { useState, useEffect } from 'react'
import { Space, Table, Modal, Button, Input, InputNumber, Select } from 'antd';
import axios from 'axios'
import { IconFont, axiosConfig, backIP, error, success } from '../common/config';
import styles from '../../styles/home/totalClassShow.scss'
import { getToken } from '../common/util';
import { houseItemConfig } from './TotalInfoShow';
const { Option } = Select;

interface classItemConfig {
    key: number,
    class_name: string,
    seat_number: string,
}

interface courseConfig {
    course: number, // 所属哪节课
    result: boolean, // 该节课是否已经被人审核
}

interface classDetailConfig {
    name: string,
    seat_number: string,
    house: string,
    house_id: number,
    floor: number, // 教室所处楼层
    first?: courseConfig, // 第一二节课是否被申请
    second?: courseConfig,
    third?: courseConfig,
    fourth?: courseConfig,
}

interface TotalClassShowConfig {
    houseIndex: number | null
    selectFloor: number | null
    houseList: houseItemConfig[]
    addIndex: number
    setAddIndex: React.Dispatch<React.SetStateAction<number>>
}

export default function TotalClassShow({ houseIndex, selectFloor, houseList, addIndex, setAddIndex }: TotalClassShowConfig) {
    const [classList, setClassList] = useState<classItemConfig[]>([])
    const [editClassID, setEditClassID] = useState<number | null>(null)
    const [classDetail, setClassDetail] = useState<classDetailConfig | null>(null)
    const [selectHouseValue, setSelectHouseValue] = useState<number | null>(null)
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const [name, setName] = useState('')
    const [seatNum, setSeatNum] = useState(0)
    const [floor, setFloor] = useState(0)
    useEffect(() => {
        getClassList()
    }, [houseIndex, selectFloor])
    useEffect(() => {
        getDetail()
    }, [editClassID])
    useEffect(() => {
        if (addIndex === 2) {
            setVisible(true)
            setClassDetail({
                name: '',
                seat_number: '0',
                house: '三山楼',
                house_id: 1,
                floor: 1
            })
            setSelectHouseValue(1)
            setSeatNum(0)
            setName('')
            setFloor(1)
        }
    }, [addIndex])
    const getClassList = async () => {
        if (houseIndex === null || selectFloor === null) {
            return
        }
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/basicClass`, {
            params: {
                house_id: houseIndex,
                floor: selectFloor
            },
            headers: {
                Authorization: token,
            }
        })
        const arr = res.data.map(item => {
            return {
                ...item,
                key: item.class_id
            }
        })
        setClassList(arr)
    }
    const getDetail = async () => {
        if (editClassID === null) {
            return
        }
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/detailClass`, {
            params: {
                class_id: editClassID,
            },
            headers: {
                Authorization: token,
            }
        })
        setClassDetail(res.data)
        setSelectHouseValue(res.data.house_id)
        setName(res.data.name)
        setSeatNum(Number(res.data.seat_number))
        setFloor(res.data.floor)
    }
    const handleOk = async () => {
        if (!(name && seatNum && selectHouseValue && floor)) {
            error('参数不能为空')
            return
        }
        setLoading(true)
        const token: string = getToken();
        const type = addIndex === 2 ? 'add' : 'modify'
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/class/${type}`, {
            class_id: editClassID,
            name,
            seat_number: seatNum,
            house_id: selectHouseValue,
            floor
        }, {
            headers: {
                Authorization: token
            }
        })
        res.code === 0 ? success(res.message) : error(res.message)
        getClassList();
        setVisible(false)
        setLoading(false)
        setAddIndex(null)
    }
    const getHouseSeatNum = () => {
        let selectHouseItem: houseItemConfig;
        houseList.map(houseItem => {
            if (houseItem.id === selectHouseValue) {
                selectHouseItem = houseItem
            }
        })

        if (selectHouseItem) {
            const seatShowArr = [];
            for (let index = 1; index <= selectHouseItem.floor_number; index++) {
                seatShowArr.push(
                    <Option key={index} value={index}>{`第${index}层`}</Option>
                )
            }
            return seatShowArr;
        }

        return null
    }
    const deleteClass = async (class_id) => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/class/reduce`, {
            class_id,
        }, {
            headers: {
                Authorization: token
            }
        })
        res.code === 0 ? success(res.message) : error(res.message)
        getClassList()
    }
    const columns = [
        {
            title: '教室名',
            dataIndex: 'class_name',
            width: 300,
        },
        {
            title: '座位数',
            dataIndex: 'seat_number',
            width: 300,
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: 300,
            render: (text, record: classItemConfig) => (
                <Space size="middle">
                    <IconFont
                        type='iconxiugai07'
                        className={styles.icon}
                        onClick={() => { setVisible(true); setEditClassID(record.key) }}
                    />
                    <IconFont type='iconshanchu' className={styles.icon} onClick={() => { deleteClass(record.key) }} />
                </Space>
            ),
        },
    ];
    return (
        <>
            <Table columns={columns} dataSource={classList} />
            <Modal
                visible={visible}
                onOk={handleOk}
                footer={[
                    <Button key="back" onClick={() => setVisible(false)}>
                        取消
                  </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                        {addIndex === 2 ? '增加' : '修改'}
                    </Button>,
                ]}
                onCancel={() => setVisible(false)}
            >
                {
                    classDetail && <>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>教室名：</div>
                            <Input placeholder="请输入教室名" value={name} onChange={(e) => { setName(e.target.value) }} />
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>座位数：</div>
                            <InputNumber placeholder="请输入座位数" style={{
                                width: 420
                            }} value={Number(classDetail.seat_number)} onChange={(e) => { setSeatNum(Number(e)) }} />
                        </div>
                        <div className={styles.inputLayout} style={{
                            justifyContent: 'space-between'
                        }}>
                            <div className={styles.floor}>
                                <div style={{
                                    width: 67
                                }}>教学楼：</div>
                                <Select
                                    defaultValue={classDetail.house}
                                    style={{ width: 120 }}
                                    onChange={(value: any) => { setSelectHouseValue(value) }}
                                >
                                    {
                                        houseList.map(houseItem => {
                                            return <Option key={houseItem.id} value={houseItem.id}>{houseItem.value}</Option>
                                        })
                                    }
                                </Select>
                            </div>
                            <div className={styles.floor}>
                                <div style={{
                                    width: 67
                                }}>楼层：</div>
                                <Select
                                    defaultValue={`第${classDetail.floor}层`}
                                    style={{ width: 120 }}
                                    onChange={(value: any) => { setFloor(value) }}
                                >
                                    {getHouseSeatNum()}
                                </Select>
                            </div>
                        </div>
                    </>
                }
            </Modal>
        </>
    )
}
